package segger.vasttrafik.io;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import javax.xml.parsers.ParserConfigurationException;

import org.apache.log4j.Logger;
import org.xml.sax.SAXException;

import segger.vasttrafik.parsing.XMLParseHandler;
import segger.vasttrafik.parsing.XMLParser;

public class HttpConnection {
    private static final Logger logger = Logger.getLogger(HttpConnection.class);
    
    public static final String getResponseAsText(String urlAsStr) throws MalformedURLException, IOException {
        URL url = new URL(urlAsStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        
        if(conn.getResponseCode() != 200) {
            logger.debug("throw");
            throw new IOException(conn.getResponseMessage());
        }
        
        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder builder = new StringBuilder();
        String line;
        while((line = br.readLine()) != null) {
            builder.append(line);
        }
        br.close();
        conn.disconnect();
        String response = builder.toString();
        logger.info("Read response");
        logger.debug(response);
        return response;
    }
    
    public static final void getParsedReponse(String urlAsStr, XMLParseHandler handler) throws IOException, ParserConfigurationException, SAXException {
        URL url = new URL(urlAsStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        
        if(conn.getResponseCode() != 200) {
            logger.debug("throw");
            throw new IOException(conn.getResponseMessage());
        }
        
        XMLParser.parseFromInputStream(conn.getInputStream(), handler);
    }
}
